'use strict';
exports.main = async (event, context) => {
	const db = uniCloud.database();
	const {
		content,
		author_id,
		author_name,
		author_avatar,
		target_id,
		parent_id = ''
	} = event;

	// 这里用 new Date()，保证类型正确
	const now = new Date();

	// 写入评论
	const res = await db.collection('user-comment').add({
		content,
		author_id,
		author_name,
		author_avatar,
		create_time: now,
		target_id,
		reply_count: 0,
		like_count: 0,
		parent_id
	});

	// 更新帖子评论数
	await db.collection('add-content').doc(target_id).update({
		comment_count: db.command.inc(1)
	});

	// 评论成功后，给评论者添加积分
	try {
		await uniCloud.callFunction({
			name: 'scoreManager',
			data: {
				action: 'post_create', // 评论也算是一种内容创建
				userId: author_id,
				data: {
					postId: res.id
				}
			}
		})
	} catch (scoreError) {
		console.error('评论积分计算失败:', scoreError)
		// 积分计算失败不影响评论成功
	}

	// 创建评论通知（如果评论的不是自己的帖子）
	try {
		// 获取帖子信息
		const postRes = await db.collection('add-content').doc(target_id).get();
		const postInfo = postRes.data[0] || {};
		const postAuthorId = postInfo.user_id; // 修正：使用 user_id 字段

		console.log('【user-comment】帖子信息:', {
			postId: target_id,
			postAuthorId: postAuthorId,
			commentAuthorId: author_id,
			isSelfComment: postAuthorId === author_id
		});

		// 如果评论的不是自己的帖子，创建通知
		if (postAuthorId && postAuthorId !== author_id) {
			console.log('【user-comment】开始创建评论通知');
			
			await uniCloud.callFunction({
				name: 'createMessageNotification',
				data: {
					postId: target_id,
					senderId: author_id,
					receiverId: postAuthorId,
					actionType: 'comment',
					postTitle: postInfo.title || postInfo.content?.substring(0, 20) + '...' || '帖子'
				}
			});
			
			console.log('【user-comment】评论通知创建成功');
		} else {
			console.log('【user-comment】自评论，跳过通知创建');
		}
	} catch (notificationError) {
		console.error('创建评论通知失败:', notificationError);
		// 通知创建失败不影响评论成功
	}

	return {
		code: 0,
		msg: '评论成功',
		data: res
	};
};